package com.zhu.androidsample.common;

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;

import com.zhu.androidsample.common.i.IDataPresenter;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by ZCP on 2015/11/20.
 * mail:43426073@qq.com
 */
public class BaseAdapter extends RecyclerView.Adapter implements IDataPresenter {


    //
    protected List<Object> data;

    public BaseAdapter() {
        this.data = new ArrayList<>();
    }

    public BaseAdapter(List<Object> data) {
        this.data = new ArrayList<>(data);
    }


    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return null;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        ((BaseViewHolder) holder).setBean(data.get(position));
    }

    @Override
    public int getItemCount() {
        return data.size();
    }


    public boolean onItemLongClick(View itemView, int position, long id) {
        return false;
    }

    public void onItemClick(View itemView, int position, long id) {
    }

    /**
     * IDataPresenter
     **/
    @Override
    public void setData(List list) {
        data = list;
        this.notifyDataSetChanged();
    }

    @Override
    public void appendData(List list) {
        data.addAll(list);
        this.notifyDataSetChanged();
    }

    @Override
    public void removeData(int position) {
        data.remove(position);
        this.notifyItemRemoved(position);
    }

    @Override
    public void clearData() {
        data.clear();
        this.notifyDataSetChanged();

    }

    public abstract class BaseViewHolder extends RecyclerView.ViewHolder {

        public BaseViewHolder(final View itemView) {
            super(itemView);
            //设置点击事件，交给adapter中的相应方法处理
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onItemClick(itemView, getAdapterPosition(), getItemId());
                }
            });
            //设置长按点击事件，交给adapter中的相应方法处理
            itemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    return onItemLongClick(itemView, getAdapterPosition(), getItemId());
                }
            });
        }

        /**
         * 列表模型设置方法。直接将模型设置进去
         *
         * @param o 模型javaBean 用的时候强制转换
         */
        public abstract void setBean(Object o);
    }

}
